package com.puzzlebazar.client.util;

import java.util.Iterator;
import java.util.Vector;

/**
 * @author beaudoin
 *
 * A class similar to Vector<E>, only it supports concurrent read/edit 
 * from the vector.
 * @param <E> The contained type
 */
public class ConcurrentVector< E > {

	private final Vector< E > base = new Vector< E >();
	private final Vector< E > copy = new Vector< E >();
	private boolean hasChanged = false;

	public Iterator< E > iterator() {
		copyIfChanged();
		return base.iterator();
	}

	public void add( E element ) {
		hasChanged = true;
		copy.add( element );
	}

	public void remove( E element ) {
		hasChanged = true;
		copy.remove( element );
	}

	public void clear() {
		hasChanged = true;
		copy.clear();
	}

	private void copyIfChanged() {
		if( !hasChanged ) return;
		hasChanged = false;
		base.clear();
		base.addAll( copy );
	}
	
}
